<?php

/**
 * 腾讯云Upyun
 */
namespace app\helps;
use \Qcloud\Cos;
use think\File;
use think\Db;
use think\Facade\Env;
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
class Tencent {

    public function upload_tencent($file,$uid='')
    {
        //上传文件的路径
        $secretId  = Env::get('cos.secretId'); //"云 API 密钥 SecretId";
        $secretKey = Env::get('cos.secretKey'); //"云 API 密钥 SecretKey";
        $region    = Env::get('cos.region'); //设置一个默认的存储桶地域
        $bucket    = Env::get('cos.bucket'); //存储桶名称 格式：BucketName-APPID
        $size      = Env::get('cos.size'); //上传文件大小限制
        $cosClient = new Cos\Client(
            array(
                 'region' => $region,
                 'schema' => 'https', //协议头部，默认为http
                 'credentials' => array(
                 'secretId' => $secretId,
                 'secretKey' => $secretKey)));

        $info = $file->getInfo();
        $hash = $file->hash();
        $name = explode('.',$info['name']);
        $nameSize =count($name);
        //判断文件上传是否符合要求
        if($info['size'] > $size){
            return ['status'=>0,'msg'=>'文件过大'];false;
        }
        $ext = array('jpg','png','gif');
        if(!in_array($name[$nameSize-1],$ext)){
            return ['status'=>0,'msg'=>'文件类型错误'];false;
        }
        ### 上传文件流
        try {
            $key = $hash.'.'.$name[1];
            $srcPath = $info['tmp_name'];//本地文件绝对路径
            $files = fopen($srcPath, "rb");
            if ($files) {
                $result =  $cosClient->upload($bucket,$key,$file);
                //检查本地数据库是否有该文件，根据文件hash判断
                $check = Db::table('tb_file')->where('hash',$hash)->find();
                if($check){
                    $check['save_name'] = 'http://'.$bucket.'.cos.'.$region.'.myqcloud.com/'.$check['save_name'];
                    return ['status' => 1, 'msg' => '文件已存在,已返回ID','data'=> $check,'pic'=>$check['id']];die;
                }
                //存本地数据库
                $arr = array();
                $arr['extension'] = $name[1];
                $arr['save_name'] = $key;
                $arr['file_name'] = $result['Location'];
                $arr['hash'] = $hash;
                $arr['type'] = 1;
                $arr['uid'] = $uid?$uid:0;
                $arr['time'] = time();
                $insert = Db::table('tb_file')->insertGetId($arr);
                if($insert){
                    $arr['save_name'] = 'http://'.$bucket.'.cos.'.$region.'.myqcloud.com/'.$arr['save_name'];
                    return ['status' => 1, 'msg' => '图片上传成功','data'=> $arr,'pic'=>$insert];
                }else{
                    return ['status' => 0, 'msg' => '入库失败'];
                }
            }
        } catch (\Exception $e) {
            return ['status'=>0,'msg'=>'上传异常'.$e->getMessage()];false;
        }
    }

}
